package com.frame.platform.rank;

import java.util.*;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.frame.database.DataBase;
import com.frame.database.DbOperate;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.database.util.ConditionMap;
import com.frame.database.util.Seq;
import com.frame.hibernate.HibernateUtil;

public class RankDao {

	public RankDao(){

	}
	public Integer addRank(Wfrank rank) throws HibernateException, Exception{
		JdataBean bean=new JdataBean();
		bean.put("rankid", new Seq().getKeyId("Wfrankid"));
		bean.put("rankname", rank.getRankname());
		bean.put("rankdesc", rank.getRankdesc());
		DbOperate.getInstance().saveBean("Wfrank", bean.getDataMap());
//        DataBase.getInstance().save(rank);
		return new Integer(bean.getString("rankid"));
	}

	public Wfrank getRank(Integer rabkId) throws HibernateException, Exception{
		return (Wfrank)DataBase.getInstance().getBean(Wfrank.class, rabkId);
	}
	public void updateRank(Wfrank rank){
		Session session=HibernateUtil.currentSession();
		Transaction transaction=session.beginTransaction();
		Wfrank loadrank=(Wfrank)session.load(Wfrank.class, rank.getRankid());
		loadrank.setRankname(rank.getRankname());
		loadrank.setRankdesc(rank.getRankdesc());
		loadrank.setRankcode(rank.getRankcode());
		session.flush();
		transaction.commit();
		HibernateUtil.closeSession();
	}

	public void delRank(String[] rankId) throws HibernateException, Exception{
//		DataBase data=DataBase.getInstance();
		DbOperate db=DbOperate.getInstance();
		for(int i=0;i<rankId.length;i++){
//			Wfrank rank=new Wfrank();
//			rank.setRankid(new Integer(rankId[i]));
//			rank.setRankname("");
//			data.delete(rank);
			db.delete("delete from Wfrank where rankid=?", new Object[]{rankId[i]});
		}
	}

	public PageResult getRankList(String rankName,int size,int pageNo) throws Exception{
		ConditionMap map=new ConditionMap();
		if(rankName!=null){
			map.put("rankname like ?").setParameter( "%"+rankName+"%");
		}
		map.addOrder("ordernum", true);
		map.addOrder("rankid", true);
		PageResult pr=DataBase.getInstance().query("Wfrank", map,size,pageNo);
		return pr;
	}

	public void addRankMenu(String[] menuId,Integer rankId) throws HibernateException, Exception{
		DataBase data=DataBase.getInstance();
		data.deleteBatch("Wfrankmenu","rankId", new Object[]{rankId});
		DbOperate db=DbOperate.getInstance();
		if(menuId!=null){
			for(int i=0;i<menuId.length;i++){
//                WfrankmenuId rmid=new WfrankmenuId(rankId,menuId[i]);
//                Wfrankmenu rm=new Wfrankmenu();
//                rm.setId(rmid);
//                data.save(rm);
				JdataBean bean=new JdataBean();
				bean.put("rankId", rankId);
				bean.put("menuId", menuId[i]);
				db.saveBean("Wfrankmenu",bean.getDataMap());
			}
		}
	}
}
